package com.motorola.dp.jenkinsmonitor.service.entity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.motorola.dp.jenkinsmonitor.model.entity.Customer;
import com.motorola.dp.jenkinsmonitor.model.util.collections.Predicate;
import com.motorola.dp.jenkinsmonitor.model.util.collections.Transformer;
import com.motorola.dp.jenkinsmonitor.model.util.svn.SvnModule;
import com.motorola.dp.jenkinsmonitor.model.util.svn.SvnModules;
import com.motorola.dp.jenkinsmonitor.service.util.collections.CollectionsService;
import com.motorola.dp.jenkinsmonitor.service.util.svn.SvnService;

@Service("customerService")
public class DefaultCustomerService implements CustomerService {

    private static final String CUSTOMER_MODULE_PREFIX = "dpcust_";

    @Value("#{svnService}")
    private SvnService svnService;

    @Value("#{collectionsService}")
    private CollectionsService collectionsService;

    public List<SvnModule> fetchCustomerModulesFromSvn(String customerName) {
        String moduleName = CUSTOMER_MODULE_PREFIX + customerName;
        SvnModules modules = svnService.parseRemoteSvnXml(moduleName, "modules.xml", SvnModules.class);
        return modules.getModules();
    }

    public List<Customer> fetchCustomerList() {
        List<String> folderNames = svnService.getFolderNames("");
        Collection<String> customerNames = collectionsService
                .filterAndTransform(folderNames, isCustomerName(), removeCustomerPrefixesAndSlashes());

        List<Customer> result = createCustomersFrom(customerNames);
        return result;
    }

    private static Predicate<String> isCustomerName() {
        return new Predicate<String>() {
            public boolean applies(String object) {
                return object.startsWith(CUSTOMER_MODULE_PREFIX);
            }
        };
    }

    private static Transformer<String> removeCustomerPrefixesAndSlashes() {
        return new Transformer<String>() {
            public String transform(String object) {
                return object.replace(CUSTOMER_MODULE_PREFIX, "").replace("/", "");
            }
        };
    }

    private List<Customer> createCustomersFrom(Collection<String> customerNames) {
        List<Customer> result = new ArrayList<Customer>();
        for (String customerName : customerNames) {
            Customer c = new Customer(customerName);
            result.add(c);
        }
        return result;
    }

    public void setSvnService(SvnService svnService) {
        this.svnService = svnService;
    }

    public void setCollectionsService(CollectionsService collectionsService) {
        this.collectionsService = collectionsService;
    }
}
